package com.wugh.fast.demo.config;

import com.google.common.collect.Lists;
import com.wugh.fast.demo.config.bean.ResponseDecoder;
import com.wugh.fast.kernel.core.thread.ContextAwareCallable;
import com.wugh.fast.kernel.core.thread.ContextHandler;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 说明:
 *
 * @author wugh
 * @date 2020-01-15 16:38
 */
@Configuration
public class BeanConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    /**
     * 添加feignClient的响应解析器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public Decoder feignDecoder() {
        return new ResponseDecoder(
                new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
    }

    /**
     * 初始化上下文解析器
     *
     * @return
     */
    @Bean
    public CommandLineRunner initContextHandler() {
        return args -> {
            ContextHandler<RequestAttributes> contextHandler = new ContextHandler<RequestAttributes>() {
                @Override
                public RequestAttributes getContext() {
                    return RequestContextHolder.getRequestAttributes();
                }

                @Override
                public void setContext(RequestAttributes context) {
                    RequestContextHolder.resetRequestAttributes();
                    RequestContextHolder.setRequestAttributes(context);
                }

                @Override
                public void cleanContext() {
                    RequestContextHolder.resetRequestAttributes();
                }
            };
            ContextAwareCallable.setDefaultHandlers(Lists.newArrayList(contextHandler));
        };
    }
}
